package com.tcgroup.phone.base_core.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import androidx.annotation.IdRes;

import com.tcgroup.phone.base_core.utils.KLog;
import com.tcgroup.phone.base_core.widget.factory.AbRadioGroupViewFactory;
import com.tcgroup.phone.base_core.widget.model.SmartRadioGroupModel;

import java.util.ArrayList;

/**
 * 作者: wangfei
 * 创建时期: 2020/4/22.
 * 包名: com.tcgroup.phone.base_core.widget
 * 类名: OSAndroidMvvm
 * 单选 自动换行
 */
public class SmartRadioGroup extends RadioGroup {

    ArrayList<SmartRadioGroupModel> models;
    OnCheckedChangeListener onCheckedChangeListener;

    public SmartRadioGroup(Context context) {
        super(context);
        initView();
    }

    public SmartRadioGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //获取总宽度,是包含padding值
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        //调用ViewGroup的方法，测量子view
        measureChildren(widthMeasureSpec,heightMeasureSpec);

        //最大的宽
        int maxWidth = 0;
        int maxHeight = 0;
        //当前这一行的累计行宽
        int maxLineWidth = 0;
        //当前这行的最大行高
        int maxLineHeight = 0;
        //用于记录换行前的行宽和行高
        int oldHeight;
        int oldWidth;


        int count = getChildCount();
        //假设 widthMode和heightMode都是AT_MOST
        for (int i = 0;i < count;i++){
            RadioButton child = (RadioButton) getChildAt(i);
            int leftMargin = 0;
            int rightMargin = 0;
            int topMargin = 0 ;
            int bottomMargin = 0;
            MarginLayoutParams childParams = (MarginLayoutParams) child.getLayoutParams();
            leftMargin = childParams.leftMargin;
            rightMargin = childParams.rightMargin;
            topMargin = childParams.topMargin;
            bottomMargin = childParams.bottomMargin;
            //得到这一行的最高
            oldHeight = maxLineHeight;
            //记录每次换行后上一行的最大宽度
            oldWidth = maxWidth;
            //获取当前view的所占的宽度
            int deltaX = child.getMeasuredWidth() + leftMargin + rightMargin;
            int deltaY = child.getMeasuredHeight() + topMargin + bottomMargin;
            if (maxLineWidth + deltaX + getPaddingLeft() + getPaddingRight() > widthSize) {
                //和目前最大的宽度比较,得到最宽。不能加上当前的child的宽,所以用的是oldWidth
                maxWidth = Math.max(maxLineWidth, oldWidth);
                maxLineWidth = deltaX;
                //累加高度
                maxHeight += oldHeight;
                //重置行高,当前这个View，属于下一行，因此当前最大行高为这个child的高度加上margin
                maxLineHeight = deltaY;
            }else {
                //不换行，累加宽度
                maxLineWidth += deltaX;
                //不换行，计算行最高
                maxLineHeight = Math.max(maxLineHeight,deltaY);
            }
            if (i == count - 1) {
                //前面没有加上下一行的搞，如果是最后一行，还要再叠加上最后一行的最高的值
                maxHeight += maxLineHeight;
                //计算最后一行和前面的最宽的一行比较
                maxWidth = Math.max(maxLineWidth, oldWidth);
            }
        }

        //加上当前容器的padding值
        maxHeight += getPaddingTop() + getPaddingBottom();
        maxWidth += getPaddingLeft() + getPaddingRight();
        setMeasuredDimension(widthMode == MeasureSpec.EXACTLY ? widthSize : maxWidth,
                heightMode == MeasureSpec.EXACTLY ? heightSize : maxHeight);

    }

    @Override
    protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed) {
        super.measureChildWithMargins(child, parentWidthMeasureSpec, widthUsed, parentHeightMeasureSpec, heightUsed);
        KLog.i("measureChildWithMargins"+child.getMeasuredWidth()+
                "margin"+((MarginLayoutParams)child.getLayoutParams()).leftMargin);
    }

    @Override
    protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) {
        super.measureChildren(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) {
        super.measureChild(child, parentWidthMeasureSpec, parentHeightMeasureSpec);
        KLog.i("measureChild"+child.getMeasuredWidth()
        +"margin"+((MarginLayoutParams)child.getLayoutParams()).leftMargin);

    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int count = getChildCount();
        //pre为前面所有的child的相加后的位置
        int preLeft = getPaddingLeft();
        int preTop = getPaddingTop();
        int maxHeight = 0;
        for (int i = 0;i< count;i++){
            RadioButton child = (RadioButton) getChildAt(i);
            int leftMargin = 0;
            int rightMargin = 0;
            int topMargin = 0 ;
            int bottomMargin = 0;
            MarginLayoutParams childParams = (MarginLayoutParams) child.getLayoutParams();
            leftMargin = childParams.leftMargin;
            rightMargin = childParams.rightMargin;
            topMargin = childParams.topMargin;
            bottomMargin = childParams.bottomMargin;
            //r-l为当前容器的宽度。如果子view的累积宽度大于容器宽度，就换行。
            if (preLeft + leftMargin + child.getMeasuredWidth()
                    + rightMargin + getPaddingRight() > (r - l)){
                //换行重置
                preLeft = getPaddingLeft();
                preTop += maxHeight;
                maxHeight = child.getMeasuredHeight() + topMargin + bottomMargin;
            }else {//不换行,计算最大高度
                maxHeight = Math.max(maxHeight,child.getMeasuredHeight() +
                        topMargin + bottomMargin);
            }
            //left坐标
            int left = preLeft + leftMargin;
            int right = left + child.getMeasuredWidth();
            //top坐标
            int top = preTop + topMargin;
            //bottom
            int bottom = top + child.getMeasuredHeight();
            //为子view布局
            child.layout(left,top,right,bottom);


            //计算布局结束后，preLeft的值
            preLeft += leftMargin + child.getMeasuredWidth() + rightMargin;
        }
    }

    public ArrayList<SmartRadioGroupModel> getModels() {
        return models;
    }

    public void setModels(ArrayList<SmartRadioGroupModel> models) {
        this.models = models;
        if (models == null || models.size() <= 0){
            return;
        }
        for (SmartRadioGroupModel model : models){
            AbRadioGroupViewFactory factory = new AbRadioGroupViewFactory();
            addView(factory.inflateView(getContext(),model));
        }
    }

    public void initView(){
        this.setOnCheckedChangeListener((group, checkedId) ->
                        onCheckedChangeListener.onCheckedChanged(group,checkedId,(SmartRadioGroupModel)findViewById(checkedId).getTag()));
    }


    public interface OnCheckedChangeListener{
        void onCheckedChanged(RadioGroup group, @IdRes int checkedId,SmartRadioGroupModel model);
    }

    public OnCheckedChangeListener getOnCheckedChangeListener() {
        return onCheckedChangeListener;
    }

    public void setOnCheckedChangeListener(OnCheckedChangeListener onCheckedChangeListener) {
        this.onCheckedChangeListener = onCheckedChangeListener;
    }
}
